using System.Collections;
using System.Collections.Generic;

namespace ColladaDotNet.SimpleMesh
{
	public class IndexBufferMap : IEnumerable<MaterialLink>
	{
		private readonly VertexBuffer buffer;

		readonly List<MaterialLink> list = new List<MaterialLink>();

		readonly Dictionary<object, MaterialLink> map = new Dictionary<object, MaterialLink>();

		public IndexBufferMap(VertexBuffer buffer)
		{
			this.buffer = buffer;
		}

		public IndexBuffer this[object key]
		{
			get
			{
				MaterialLink buf;
				if (!map.TryGetValue(key,out buf))
				{
					buf = new MaterialLink() { IndexBuffer = new IndexBuffer(buffer) ,Key = key};
					list.Add(buf);
					map.Add(key,buf);
				}
				return buf.IndexBuffer;
			}
		}

		public int Count
		{
			get
			{
				return list.Count;
			}
		}


		public object GetKey(int i)
		{
			return list[i].Key;
		}

		public IndexBuffer GetIndexBuffer(int i)
		{
			return list[i].IndexBuffer;
		}

		public bool HaveCommonKeysWith(IndexBufferMap meshes)
		{
			foreach (var pair in map)
			{
				foreach (var valuePair in meshes.map)
				{
					if (pair.Key == valuePair.Key)
						return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Returns an enumerator that iterates through the collection.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> that can be used to iterate through the collection.
		/// </returns>
		/// <filterpriority>1</filterpriority>
		IEnumerator<MaterialLink> IEnumerable<MaterialLink>.GetEnumerator()
		{
			return list.GetEnumerator();
		}

		public IEnumerator GetEnumerator()
		{
			return list.GetEnumerator();
		}
	}
}